package com.automapper.sqlbuilder.impl;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.automapper.criterion.Criterion;
import com.automapper.criterion.ExpressionContext;
import com.automapper.criterion.SqlAssemble;
import com.automapper.query.CriteriaImpl;
import com.automapper.sqlbuilder.SqlBuilderTemplate;
import com.automapper.utils.ParameterUtils;
import com.automapper.utils.PropertiesFacade;

public class SelectSqlBuilder extends SqlBuilderTemplate {	
	
	@Override
	public String buildSql(Object parameterObject, PropertiesFacade propertiesFacade) throws Exception {  
		StringBuilder sql = new StringBuilder();
		Map<String, Object> parameterMap = (Map<String, Object>) parameterObject;
		//获取传入参数
		CriteriaImpl criteria = (CriteriaImpl) ParameterUtils.getParameter(parameterMap);
		SqlAssemble sqlAssemble = criteria.getSqlAssemble();
					
		sql.append("select ")
		   .append(StringUtils.join(sqlAssemble.assembleColumn(), ","))
		   .append(" from ")
		   .append(StringUtils.join(sqlAssemble.assembleTable(), ","))
		   .append(" where 1 = 1 ");
		
		ExpressionContext allExpression = ((CriteriaImpl) criteria).getExpressionContext();
		for (int i = 0; i < allExpression.getExpressionList().size(); i++) {
			Criterion expression = allExpression.getExpressionList().get(i);
			sql.append(" and ")
			   .append(expression.toSqlString());
			
//			parameterMap.put(expression.getParameterAliases(), expression.getValue());
			parameterMap.putAll(expression.getValues());
		}
		
		if (allExpression.getPageExpression() != null) {
			sql.append(" " + allExpression.getPageExpression().toSqlString());
		}
		
		return sql.toString();
	}  
}
